﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Ehai.Web.Framework.Rules
{
    class InsertSelectRuleHandle:Rules.IMsgRuleHandle
    {
        #region IMsgRuleHandle 成员
        public const string Name = "insertselect";
#if DEBUG
        private int _execStatus=0;
        public int ExecStatus
        {
            get { return _execStatus; }
        }
#endif
        /// <summary>
        /// 把数据插入数据库或更新记录
        /// </summary>
        /// <param name="p">
        /// 0:(必选)处理类型
        /// 1:(必选)表名
        /// 2:(必选)列名（多个列名","隔开）
        /// 3:(必选)select语句
        /// 4:(可选)使用的连接字符串(id)
        /// </param>
        /// <param name="ci">环境变量</param>
        /// <example>
        /// string[] test = { "insertSelect", "DMMessage", "content,deleteStatus,createUserID,LatestNodeId", "select content,deleteStatus,createUserID,LatestNodeId from DMMessge where deleteStatus=0" };
        /// InsertSelect(test,ci);
        /// </example>
        /// <exception cref="Ehai.Web.Framework.WebException">
        /// Ehai.Web.Framework.WebException:数据插入数据库或更新记录错误;
        /// </exception>
        /// <returns>
        /// [0][0]中的值代表操作结果,succeeded,failed
        /// 基本条件不满足返回null
        /// </returns>
        public string[][] Execute(string[] p, ContextInfo ci)
        {
            if (p.Length < 4 )
            {
#if DEBUG
                // 数组长度没达到要求
                _execStatus = -2;
#endif
                return null;
            }
            if (String.IsNullOrEmpty(p[1]))
            {
#if DEBUG
                //  第一个参数没达到要求
                _execStatus = 1;
#endif
                return null;
            }
            if (String.IsNullOrEmpty(p[2]))
            {
#if DEBUG
                //  第二个参数没达到要求
                _execStatus = 2;
#endif
                return null;
            }
            if (String.IsNullOrEmpty(p[3]))
            {
#if DEBUG
                //  第三个参数没达到要求
                _execStatus = 3;
#endif
                return null;
            }
            string constr = (p.Length < 5) ?String.Empty :p[4] ;
            try
            {
                int suc = -1;
                string sql = "";                //存储插入选择的sql语句
                ApplicationDB acsSql = null;
                string Logsql = "";
                ApplicationDB LogacsSql = null;
                string[][] result = { new String[] { String.Empty } };
                sql = "insert into " + p[1] + "(" + p[2] + ") " + p[3] + "";
                acsSql = new ApplicationDB(sql, ci, constr);
                suc = acsSql.ExecuteNonQuery();
                if (suc != -1)
                {
                    Logsql = "insert into log(Msg,UserName,Ip,BrowserName,BrowserVersion,BrowserPlatform,operationTime)" +
                        "values('" + sql.Replace("'", "\\''").Replace("\"", "\\\"") + "','" + ci.Session["username"] + "','" + ci.Request.UserHostAddress +
                        "','" + ci.Request.Browser.Browser + "','" + ci.Request.Browser.Version + "','" +
                        ci.Request.Browser.Platform + "','" + DateTime.Now.ToString() + "')";
                    LogacsSql = new ApplicationDB(Logsql, ci, "EhaiAMS");
                    int t = LogacsSql.ExecuteNonQuery();
                    if (t != 1)
                        throw new Exception("数据插入数据库或更新记录操作写入日志出错,返回操作数：" + t);
                    result[0][0] = "succeeded";
                }
                else
                {
                    result[0][0] = "failed";
                }
#if DEBUG
                // 操作成功,状态值
                _execStatus = 0;
#endif
                return result;
            }

            catch (Exception ex)
            {
#if DEBUG
                // 抛出异常
                _execStatus = -1;
#endif
                throw new Ehai.Web.Framework.WebException("Ehai.WebFramework.SelectRule", "数据插入数据库或更新记录错误！", ex);
            }
        }

        public string GetHelpInfo()
        {
            return "插入更新记录";
        }

        public string GetHelpDetail()
        {
            return "把数据插入数据库或更新记录,例子：{insertselect, table ,列名c1,...,cn,select语句}<br/>";
        }

        public string[] GetParametersInfo()
        {
            string[] p = new string[4];
            p[0] = "（必选）处理类型";
            p[1] = "（必选）表名";
            p[2] = "（必选）列名（多个列名', '隔开）";
            p[3] = "（必选）select语句";
            p[4] = "（可选）使用的连接字符串(id)";
            return p;
        }

        #endregion
    }
}
